package MyGO.controller;

import MyGO.Form.TrackForm;
import MyGO.Main;
import MyGO.dao.IMedicineDao;
import MyGO.dao.impl.MedicineImpl;
import MyGO.property.Medicine;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
import lombok.Getter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static MyGO.utils.ArrayfilterUtils.ArrayfilterUtils.FilterMedicineByPinYinAndMedcineName;

public class Yaoku_guanli {

    @FXML
    private TextField bianhao;

    @FXML
    private Button jia;

    @FXML
    private TextField mingcheng;

    @FXML
    private Button sure;

    @FXML
    private TableView<Medicine> yao;

    @FXML
    private TextField zhujima;

    @Getter
    private static Stage newsStage = new Stage();
    private List<Medicine> list2 = new ArrayList<>(); //目前的药库
    private IMedicineDao temp = new MedicineImpl(); //总药库
    @Getter
    private static Medicine medicine = null;

    public void initialize() {
        //引入药库
        list2 = temp.getMedicineList();
        showMedicine();
        //动态查询,不支持编号搜索
        //名称
        mingcheng.textProperty().addListener((observable, oldValue, newValue) -> {
            list2 = FilterMedicineByPinYinAndMedcineName(temp.getMedicineList(), newValue, zhujima.getText());
            yao.getColumns().clear();
            if (list2 != null){
                showMedicine();
            }
        });
        //拼音
        zhujima.textProperty().addListener((observable, oldValue, newValue) -> {
            list2 = FilterMedicineByPinYinAndMedcineName(temp.getMedicineList(), mingcheng.getText(), zhujima.getText());
            yao.getColumns().clear();
            if (list2 != null){
                showMedicine();
            }
        });

        //精准搜索
        sure.setOnAction(e -> {
            if (bianhao.getText().isEmpty() || mingcheng.getText().isEmpty() || zhujima.getText().isEmpty()) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setContentText("请输入搜索信息！");
                alert.showAndWait();
            } else {
                //添加药品

                //编号搜索
                if (!bianhao.getText().isEmpty()){
                    for (var t:list2){
                        if (t.getId().equals(bianhao.getText())){
                            list2.clear();
                            list2.add(t);
                            break;
                        }
                    }
                }
                //拼音搜索
                else if (!zhujima.getText().isEmpty()){
                    for (var t:list2){
                        if (t.getHelpCode().equals(zhujima.getText())){
                            list2.clear();
                            list2.add(t);
                            break;
                        }
                    }
                }
                //名字搜索
                else if (!mingcheng.getText().isEmpty()){
                    for (var t:list2){
                        if (t.getName().equals(mingcheng.getText())){
                            list2.clear();
                            list2.add(t);
                            break;
                        }
                    }
                }
            }
            yao.getColumns().clear();
            showMedicine();
        });
        //添加药品
        jia.setOnAction(e -> {
            // 弹出弹窗
            newsStage.setResizable(false);
            FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getResource("/MyGO/fxml/yaowu_genggai.fxml"));
            Scene scene = null;
            try {
                scene = new Scene(fxmlLoader.load());
            } catch (IOException ev) {
                throw new RuntimeException(ev);
            }
            newsStage.setScene(scene);
            newsStage.show();
            //关闭后自动更新信息
            newsStage.setOnHidden(e1 ->{
                yao.getColumns().clear();
                list2 = temp.getMedicineList();
                showMedicine();
            });
        });
    }

    private void showMedicine() {

        //设置显示界面
        TableColumn<Medicine, Number> indexColumn = new TableColumn<>("编号");
        indexColumn.setSortable(false);
        indexColumn.setCellFactory(column -> new TableCell<Medicine, Number>() {
            @Override
            protected void updateItem(Number item, boolean empty) {
                super.updateItem(item, empty);

                if (empty || getIndex() < 0) {
                    setText(null);
                } else {
                    setText(Integer.toString(getIndex() + 1));
                }
            }
        });

        // 确保编号列是第一列
        yao.getColumns().add(0, indexColumn);
        //添加其他列
        TableColumn<Medicine, String> nameColumn = new TableColumn<>("名称");
        TableColumn<Medicine, String> idColumn = new TableColumn<>("编码");
        TableColumn<Medicine, String> sizeColumn = new TableColumn<>("规格");
        TableColumn<Medicine, String> buildColumn = new TableColumn<>("厂家");
        TableColumn<Medicine, String> priceColumn = new TableColumn<>("价格");
        nameColumn.setPrefWidth(100);
        idColumn.setPrefWidth(300);
        sizeColumn.setPrefWidth(100);
        buildColumn.setPrefWidth(200);
        priceColumn.setPrefWidth(100);

        nameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getName()));
        idColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getId()));
        sizeColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getFormat()));
        buildColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getManufacturer()));
        priceColumn.setCellValueFactory(cellData -> new SimpleStringProperty(String.valueOf(cellData.getValue().getPrice())));
        ObservableList<Medicine> data = FXCollections.observableArrayList(list2);
        yao.setItems(data);
        yao.getColumns().addAll(idColumn,nameColumn,sizeColumn,buildColumn,priceColumn);

        // 设置按钮
        TableColumn<Medicine, Void> actionCol = new TableColumn<>("操作");

        actionCol.setCellFactory(param -> {
            Button deleteButton = new Button("更改");
            TableCell<Medicine, Void> cell = new TableCell<Medicine, Void>() {
                @Override
                protected void updateItem(Void item, boolean empty) {
                    super.updateItem(item, empty);

                    if (empty) {
                        setGraphic(null);
                    } else {
                        setGraphic(deleteButton);
                    }
                }
            };

            deleteButton.setOnAction(event -> {
                // 获取当前行的数据
                medicine = cell.getTableRow().getItem();
                if (medicine != null) {
                    // 弹出弹窗
                    FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getResource("/MyGO/fxml/yaowu_genggai.fxml"));
                    Scene scene = null;
                    try {
                        scene = new Scene(fxmlLoader.load());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    newsStage.setResizable(false);
                    newsStage.setScene(scene);
                    newsStage.show();
                    newsStage.setOnHidden(e1 ->{
                        yao.getColumns().clear();
                        list2 = temp.getMedicineList();
                        showMedicine();
                        //结束
                        medicine = null;
                    });
                }

            });
            return cell;
        });
        yao.getColumns().add(actionCol);
    }
}
